// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "libcef/browser/net_database/cef_data_base_impl.h"

#include "base/bind.h"
#include "base/logging.h"
#include "ohos_adapter_helper.h"

void TransferVector(const std::vector<std::string>& source,
                    std::vector<CefString>& target) {
  if (!target.empty())
    target.clear();

  if (!source.empty()) {
    std::vector<std::string>::const_iterator it = source.begin();
    for (; it != source.end(); ++it)
      target.push_back(*it);
  }
}

CefRefPtr<CefDataBase> CefDataBase::GetGlobalDataBase() {
  CefRefPtr<CefRequestContext> context = CefRequestContext::GetGlobalContext();
  return context ? context->GetDataBase() : nullptr;
}

bool CefDataBaseImpl::ExistHttpAuthCredentials() {
  OHOS::NWeb::OhosWebDataBaseAdapter& databaseAdapter =
  OHOS::NWeb::OhosAdapterHelper::GetInstance().GetOhosWebDataBaseAdapterInstance();
  return databaseAdapter.ExistHttpAuthCredentials();
}

void CefDataBaseImpl::DeleteHttpAuthCredentials() {
  OHOS::NWeb::OhosWebDataBaseAdapter& databaseAdapter =
  OHOS::NWeb::OhosAdapterHelper::GetInstance().GetOhosWebDataBaseAdapterInstance();
  return databaseAdapter.DeleteHttpAuthCredentials();
}

void CefDataBaseImpl::SaveHttpAuthCredentials(const CefString& host, const CefString& realm,
  const CefString& username, const char* password) {
  if (host.empty() || realm.empty() || username.empty() || password == nullptr) {
    return;
  }
  OHOS::NWeb::OhosWebDataBaseAdapter& databaseAdapter =
  OHOS::NWeb::OhosAdapterHelper::GetInstance().GetOhosWebDataBaseAdapterInstance();
  return databaseAdapter.SaveHttpAuthCredentials(host, realm, username, password);
}

void CefDataBaseImpl::GetHttpAuthCredentials(const CefString& host, const CefString& realm,
  std::vector<CefString>& username_password) {
  if (host.empty() || realm.empty()) {
    return;
  }

  std::vector<std::string> result;
  OHOS::NWeb::OhosWebDataBaseAdapter& databaseAdapter =
  OHOS::NWeb::OhosAdapterHelper::GetInstance().GetOhosWebDataBaseAdapterInstance();
  databaseAdapter.GetHttpAuthCredentials(host, realm, result);
  TransferVector(result, username_password);
  return;
}